import axios from 'axios'
import { Loading } from 'element-ui';
// import qs from 'qs';
import { mapGetters, mapMutations } from 'vuex';

// 解决中文乱码
const instance = axios.create({
	baseURL: '/dyrzj/',
	timeout: 30000,
	headers: { 'Content-Type': 'application/json' }
})
// 添加请求拦截器
instance.interceptors.request.use(
	config => {
		const token = vm.$store.getters.token
		if (token) {
			// 这里将token设置到headers中，header的key是X-TOKEN，这个key值根据你的需要进行修改即可
			config.headers['X-TOKEN'] = token;
		}
		return config
	},
	err => {
		return Promise.reject(err);
});
// 添加响应拦截器
instance.interceptors.response.use(response => {
	let data = response.data;
	let status = response.status;
	if(status===200 || status === 304){
		if(data.code == 200){
			return data;
		}else if(data.code == 403){
			vm.$router.replace('/login')
			return data;
		}
		return Promise.reject(data.message)
	}else{
		return Promise.reject(response.message)
	}
}, err => {
	if (err && err.response) {
        switch (err.response.status) {
            case 400: err.message = '请求错误(400)' ; break;
            case 401: err.message = '未授权，请重新登录(401)'; break;
            case 403: err.message = '拒绝访问(403)'; break;
            case 404: err.message = '请求出错(404)'; break;
            case 408: err.message = '请求超时(408)'; break;
            case 500: err.message = '服务器错误(500)'; break;
            case 501: err.message = '服务未实现(501)'; break;
            case 502: err.message = '网络错误(502)'; break;
            case 503: err.message = '服务不可用(503)'; break;
            case 504: err.message = '网络超时(504)'; break;
            case 505: err.message = 'HTTP版本不受支持(505)'; break;
            default: err.message = `连接出错(${err.response.status})!`;
        }
        let result = err.response.data
        if(result.error == 'Forbidden'){
          vm.$router.replace('/login')
          return
        }
    }else if(err.code == 'ECONNABORTED' && err.message.indexOf('timeout')!=-1){
		err.message = '请求超时,请稍后重试'
	}else if(err.message == 'Network Error'){
		err.message = '网络异常'
	}else{
        err.message = '连接服务器失败!'
    }
	return Promise.reject(err.message);
});

let popError = (error) => vm.$message.error(error || '');

export default {
	/**
	 * axios 封装Promise, 可以配合使用 async await
	 * @param {method: 请求方式, url: 请求接口,data: 请求参数, loading: 是否开启加载动画(默认关闭)}
	 * @param {*} succFun 请求成功后的回调函数, 如果请求失败，统一处理
	 */
	sendAxiosPromise ({
		method = 'post',
		url = '',
		data = {},
		loading = false,
    target = '',
    targetText = ''
	} = {},succFun = () => {}) {
		let load;
		if(loading){
			let option = {}
			if(target){
				option.target = target
			}else{
				option.fullscreen = true
			}
			option.text = targetText || ''
			load = Loading.service(option)
    }
    method = method.toLowerCase()
		return new Promise((resolve,reject) => {
			if(method == 'get') data = { params: data }
			instance[method](url, data).then(res => {
				loading && load.close()
				if(res.code == 200){
					succFun(res)
					resolve(res)
				}else if(res.code == 403){
          // vm.$router.replace('/login')
        }else{
					popError(res.message)
				}
			}).catch(error => {
				loading && load.close()
				popError(error)
				reject(error)
			})
		})
	},
	getJsonData ({
		loading = true,
		url = ""
	} = {},succFun = () => {}) {
		return new Promise((resolve,reject) => {
			axios({
				method: 'get',
				url: url,
				responseType:'json'
			}).then(function(res) {
				succFun(res.data)
				resolve(res.data)
			}).catch(error => {
				popError(error)
				reject(error)
			})
		})
	},
	jsonp(url){
		if(!url){
			console.error('Axios.JSONP 至少需要一个url参数!')
			return;
		}
		return new Promise((resolve,reject) => {
			window.jsonCallBack =(result) => {
				resolve(result)
			}
			var JSONP=document.createElement("script");
			JSONP.type="text/javascript";
			JSONP.src=`${url}&callback=jsonCallBack`;
			document.getElementsByTagName("head")[0].appendChild(JSONP);
			setTimeout(() => {
				document.getElementsByTagName("head")[0].removeChild(JSONP)
			},500)
		})
	},
	...mapMutations(['CLEAN_USERINFO'])
}
